package cn.tannn.surenessdemo.user.dao;

import cn.tannn.surenessdemo.user.entity.AuthResource;
import cn.tannn.surenessdemo.user.entity.AuthRoleResourceBind;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author tan
 * @date 2022-07-18 11:00:57
 */
public interface AuthRoleResourceBindDao extends JpaRepository<AuthRoleResourceBind, Long> {

    /**
     * 查询当前角色拥有的资源
     * @param roleCode roleCode
     * @return resource list
     */
    @Query("select rs from AuthResource rs, AuthRoleResourceBind bind " +
            "where rs.code = bind.resourceCode and bind.roleCode = :roleCode")
    List<AuthResource> findRoleBindResourceList(@Param("roleCode") String roleCode);


    /**
     * 查询当前角色拥有的资源 code集合
     * @param roleCode roleCode
     * @return resource list
     */
    @Query("select rs.code from AuthResource rs, AuthRoleResourceBind bind " +
            "where rs.code = bind.resourceCode and bind.roleCode = :roleCode")
    List<String> findRoleBindResourceList2Str(@Param("roleCode") String roleCode);

    /**
     * 删除roleId和resource等于这个的记录
     * @param roleCode roleCode
     * @param resourceCode resourceCode
     */
    @Modifying
    @Transactional(rollbackFor = Exception.class)
    @Query("delete from AuthRoleResourceBind bind " +
            "where bind.roleCode = :roleCode and bind.resourceCode = :resourceCode")
    void deleteRoleResourceBind(@Param("roleCode") String roleCode,@Param("resourceCode") String resourceCode);


    /**
     * 删除roleId和resource等于这个的记录
     * @param roleCode roleCode
     * @param resourceCodes resourceCodes
     */
    @Modifying
    @Transactional(rollbackFor = Exception.class)
    @Query("delete from AuthRoleResourceBind bind " +
            "where bind.roleCode = :roleCode and bind.resourceCode in (:resourceCodes) ")
    void deleteRoleResourceBind(@Param("roleCode") String roleCode,@Param("resourceCodes") List<String> resourceCodes);

    /**
     * 根据角色删除 角色-资源
     * @param roleCode roleCode
     */
    @Modifying
    @Transactional(rollbackFor = Exception.class)
    @Query("delete from AuthRoleResourceBind bind where bind.roleCode = :roleCode ")
    void deleteRoleResourceBind(@Param("roleCode") String roleCode);

}
